<template>
    <div class="container-wapper">
        <div class="component-ul">
            <ul v-loading="loading" class="LatestList">
                <li v-for="(item, index) in currentList" :key="index" class="dot">
                    <router-link tag="a" :to="'/commentpost?id=' + item.id">{{ item.title }}</router-link>
                </li>
            </ul>
            <!-- 分页 -->
            <div class="pager d-flex j-center">
                <el-pagination v-model:current-page="queryParams.pageNo" v-model:page-size="queryParams.pageSize"
                    background layout="prev, pager, next, jumper" :total="queryParams.total" />
            </div>
        </div>
    </div>

</template>


<script setup name="Nearest">
import { postApi } from '@/api';
import { computed, ref, reactive, onBeforeMount, watch } from 'vue';
import { useRouter, onBeforeRouteLeave } from 'vue-router';
import { commonMethods } from '@/utils/common';

// 公共方法和计算属性
const { formatCommentCount } = commonMethods();

// 路由
const router = useRouter();

/**
 * @name Computed
 */
// 列表左边下标显示
const indexList = computed(() => {
    return (index) => {
        return index + ((queryParams.pageNo - 1) * queryParams.pageSize);
    }
})

/**
 * @name 论坛推荐
 */
const currentList = ref([]);
const queryParams = reactive({
    isRecommend: false,
    keyword: '',
    sortField: 'createTime',
    sortOrder: 'desc',
    pageNo: 1,
    pageSize: 10,
    total: 0,
})
const loading = ref(false);
const getPostList = () => {
    loading.value = true;
    postApi.getPostList(queryParams).then((res) => {
        currentList.value = res.result.list;
        queryParams.total = parseInt(res.result.total);
    }).catch((err) => { }).finally(() => {
        loading.value = false;
    })
}

// 路由
onBeforeRouteLeave((to, from) => {
    // 如果进入的是详情页，保存页码
    if (to.path == '/commentpost') {
        sessionStorage.setItem('nearestPageNo', queryParams.pageNo);
    } else {
        sessionStorage.removeItem('nearestPageNo');
    }
})
// 生命周期
onBeforeMount(() => {
    // 获取保存的页码
    let nearestPageNo = sessionStorage.getItem('nearestPageNo');
    if (nearestPageNo && nearestPageNo != null) {
        queryParams.pageNo = Number(nearestPageNo);
        if (queryParams.pageNo == 1) {
            getPostList();
        }
    } else {
        getPostList();
    }
})

// 监听分页
watch(() => queryParams.pageNo, () => {
    getPostList();
})


// 暴露方法
const handlePageSizeChange = () => {
    queryParams.pageNo = 1;
    getPostList();
}

defineExpose({
    handlePageSizeChange
})

</script>


<style lang="less" scoped>
    .component-ul .LatestList{min-height: 200px;}
</style>